package com.Khan.controller;

import com.Khan.service.UploadService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;


/**
 * @author Khan Liu
 * @date 2022/2/15 14:55
 */
@Controller
public class FileClientController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UploadService uploadService;

    private static final String REST_URL_PREFIX = "http://FileSystemServer8002";

    @RequestMapping(value = "/")
    public String uploadPage() {
        return "index";
    }

    @RequestMapping("/getJson")
    @ResponseBody
    public ModelAndView getJson(@RequestParam("myuuid") String uuid) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index.html");
        String s = restTemplate.getForObject(REST_URL_PREFIX + "/getJson/" + uuid, String.class);
        if (s.isEmpty()) {
            mav.addObject("result_look", "查询结果为空");
            return mav;
        } else {
            mav.addObject("result_look", s);
        }
        return mav;
    }

    @RequestMapping("/getByUUID")
    @ResponseBody
    public ModelAndView getByUUID(@RequestParam("myuuid1") String uuid, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index.html");
        String s = restTemplate.getForObject(REST_URL_PREFIX + "/getFile/" + uuid, String.class);

        if (s.isEmpty()) {
            mav.addObject("result", "查询结果为空");
            return mav;
        } else {
            mav.addObject("result", "界面跳转...");
        }
        System.out.println(s);
        try{
            response.sendRedirect(s);
        } catch (IOException e){
            e.printStackTrace();
        }
        return mav;
    }

    @RequestMapping(value = "/upload",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public void upload(@RequestPart(value = "file") MultipartFile file) {
        uploadService.handleFileUpload(file);
    }

}
